package com.hcy.app.screen.cap

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import com.hcy.app.LocalNavController
import com.hcy.app.R
import com.hcy.app.api.AddSessionForm
import kotlinx.coroutines.launch

@Preview(
//    backgroundColor = 0xFF00FF00, // ARGB格式（绿色）
//    showBackground = true
)
@Composable
fun Cap_HomePre(){
    Cap_Home()
}


@OptIn(ExperimentalLayoutApi::class)
@Composable
fun Cap_Home(capViewModel: CapViewModel = hiltViewModel()){
    // 定义状态变量
    var links by remember { mutableStateOf<List<LinkDto>>(emptyList()) }
    val capState by capViewModel.capState.collectAsState()
    // 创建协程作用域
    val coroutineScope = rememberCoroutineScope()

    LaunchedEffect(Unit) { // 仅在首次组合时加载数据
        coroutineScope.launch {
            if ( capState.userInfo.isLoaded ){
                links = capViewModel.getLinks()
            }
        }
    }

    val screenWidth = LocalConfiguration.current.screenWidthDp
    val itemWidth = (screenWidth/4).dp
    val navController = LocalNavController.current
    Column(
        modifier = Modifier
            .background(Color(0xFFF7F8E5))
            .systemBarsPadding()
            .fillMaxSize()
    ) {
        // 工具栏
        Row(
            modifier = Modifier.zIndex(1f).fillMaxWidth()
                .background(Color(0xFFF6DD04)),
            verticalAlignment = Alignment.CenterVertically // 垂直居中
        ) {
            Text(
                text = "应用&链接",
                style = TextStyle(
                    fontWeight = FontWeight.Bold,
                    fontSize = 18.sp
                )
            )
            Spacer(modifier = Modifier.weight(1f)) // 关键：撑满剩余空间
            IconButton(onClick = {
                navController.navigate("home")
            }) {
                Icon(Icons.Default.Home, "首页")
            }
            IconButton(onClick = {
                coroutineScope.launch {
                    links = capViewModel.getLinks()
                }
            }) {
                Icon(Icons.Default.Refresh, "刷新")
            }
            IconButton(onClick = {
                navController.navigate("cap/setting")
            }) {
                Icon(Icons.Default.Settings, "设置")
            }
        }
        FlowRow{
            if ( links.size>0 ){
                links.forEach {
                    Column(
                        modifier = Modifier.size(itemWidth).padding(10.dp)
                            .clickable{
                                coroutineScope.launch {
                                    val sessionId= capViewModel.createCapSession(AddSessionForm(it.linkInfo.id))
                                    navController.navigate("cap/desk/${it.linkInfo.id}/$sessionId")
                                }
                            },
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        AsyncImage(
                            model = it.img,
                            contentDescription = "应用图标",
                            placeholder = painterResource( id = R.drawable.img_loding), // 加载中显示
                            error = painterResource(id = R.drawable.cloud_app),      // 失败时显示
                            modifier = Modifier.size(itemWidth-40.dp)
                        )
                        Text(
                            text = it.name,
                            modifier = Modifier.width(itemWidth-20.dp),
                            maxLines = 1, // 最多显示一行
                            overflow = TextOverflow.Ellipsis // Ellipsis-超出部分显示为...，Clip -直接截断；
                        )
                    }
                }
            }else{
                Text("暂无数据！")
            }

        }
    }
}


